<template>
	<div>
		<div class="step-box">
			<step-bar :active="active"></step-bar>
		</div>

		<div class="out">
			<div class="inner">
				<van-form validate input-align="right" error-message-align="right" @submit="onSubmit">
					<div class="box">
						<p class="contrantType">{{$t('message.cglx')}}:{{contractName}}</p>
						<p class="c-title">{{$t('addMsg.etjbxx')}}</p>
						<div class="add-title">
							<p>{{$t('message.qyf')}}</p>
						</div>
						<!-- 通过 validator 进行函数校验 -->
						<van-field :label="$t('message.jia-cg')" v-model="purchaser" maxlength="128" required :placeholder="$t('message.p-cgs')"
						 :rules="[{  required: true,message: this.$t('message.p-cgs') }]" />
						<van-field :label="$t('message.yi-gy')" required v-model="supplier" maxlength="128" :placeholder="$t('message.p-gys')"
						 :rules="[{  required: true,message: this.$t('message.p-gys') }]" />
						<!-- 新增多方 -->
						<select-item ref='select'
						v-for="(item,index) in partiesList"
						@delParties="deletParties(index)"
						:itemData="item"
						:key="item.uid">
						</select-item>
						<van-button type="warning" v-if="leg" @click="addSelect" class="addBnt" size="mini">{{$t('message.xzdf')}}</van-button>
					</div>
					<div class="box">
						<div class="add-title">
							<p>{{$t('message.xymc')}}</p>
						</div>
						<van-field :label="$t('message.name')" v-model="contractTitleCn" required :placeholder="$t('message.p-xymc')"
						 :rules="[{  required: true,message: this.$t('message.p-xymc')}]" />
						<van-field v-if="isShowEnglish" :label="$t('message.english')" v-model="contractTitleEn" :placeholder="$t('message.p-en')" :rules="[{ pattern:/^[ A-Za-z]*$/, message: this.$t('message.znsuyw'), }]" />
					</div>
					<div class="box">
						<div class="add-title">
							<p>{{$t('message.xyjbqk')}}</p>
						</div>
						<van-field :label="$t('message.xyh')" v-model="contractId" required :placeholder="$t('message.p-xyh')" :rules="[{  required: true,message: this.$t('message.p-xyh') }]" />
						<van-field readonly clickable name="datetimePicker" required :value="executionStartDate" :label="$t('message.htqx2')"
						 :placeholder="$t('message.p-starM')" @click="showPicker = true" />
						<van-popup v-model="showPicker" position="bottom">
							<van-datetime-picker v-model="currentDate" :min-date="minDate" :max-date="maxDate" type="date" @confirm="chooseStarTime" @cancel="showPicker = false" />
						</van-popup>
						<van-field readonly clickable name="datetimePicker2" :value="executionEndDate" label="" :placeholder="$t('message.p-endM')"
						 @click="showPicker2 = true" :rules="[{  required: true,message: this.$t('message.p-endM') }]" />
						<van-popup v-model="showPicker2" position="bottom">
							<van-datetime-picker v-model="currentDateEnd" :min-date="minDate" :max-date="maxDate" type="date" @confirm="chooseEndTime" @cancel="showPicker2 = false" />
						</van-popup>
					</div>
					<div class="box">
						<div class="add-title">
							<p>{{$t('message.xyje')}}</p>
						</div>
						<van-field readonly clickable required name="picker" :value="currency" :label="$t('message.bz')" :placeholder="$t('message.p-qxz')"
						 @click="showPicker3 = true" :rules="[{  required: true,message: this.$t('message.p-qxz') }]" />
						<van-popup v-model="showPicker3" position="bottom">
							<van-picker show-toolbar :columns="curreyList" @confirm="chooseCurrey" @cancel="showPicker3 = false" />
						</van-popup>
						<van-field :label="$t('message.je')" 
						:disabled="disabled" 
						v-model="amount" 
						
						type="number" 
						 @input="amountInput" required 
						 :placeholder="$t('message.p-je')" 
						 :rules="[{  required: true,message: this.$t('message.p-je') }]" />
						<van-field class="je-field" readonly :label="$t('message.zscmy')" v-model="usd" />
						<van-field class="je-field" readonly :label="$t('message.ynncjdndje')" v-model="amountPerYear" />
					</div>
					<div class="box" style="padding-bottom: 38px;">
						<div class="add-title">
							<p>{{$t('message.xynr')}}</p>
						</div>

						<van-cell-group class="none-border xynr-box">
							<van-field required readonly :label="$t('message.xynr')" />
						</van-cell-group>
						<van-cell-group error-message-align="left" class="none-border">
							<div class="out-textrea">
								<van-field v-model="content" rows="4" :autosize="true" class="textrea" maxlength="512" input-align="left" label="" type="textarea" show-word-limit
								 :placeholder="$t('message.p-xybr')" :rules="[{ required: true,message: this.$t('message.p-xybr') }]" />
							</div>
						</van-cell-group>
						<upload-file ref='uploadFile' :pfileList="cfileList" class="upload-btn"></upload-file>
					</div>
					<div style="margin:38px 16px 16px 16px;">
						<van-button round block class="save" type="info" native-type="button" :disabled="disabledBnt" :loading="disabledBnt"
						 @click="save">{{$t('message.zc')}}</van-button>
						<div style="overflow: hidden;margin-top: 10px;padding-bottom: 40px;">
							<van-button class="mybnt" style="float: left;" @click="beforBnt" native-type="button">{{$t('addMsg.syb')}}</van-button>
							<van-button class="mybnt" style="float: right;" round native-type="submit">{{$t('addMsg.xyb')}}</van-button>
						</div>
					</div>

				</van-form>
			</div>
		</div>
	</div>
</template>

<script>
	import buried from "@/utils/buried";
	import SelectItem from "@/components/select"
	import uploadFile from "@/components/uploadFile"
	import NavBar from "@/components/NavBar";
	import StepBar from "@/components/StepBar";
	import {
		Dialog
	} from 'vant';
	let nub = 0
	export default {
		components: {
			SelectItem,
			uploadFile,
			NavBar,
			StepBar,
			[Dialog.Component.name]: Dialog.Component,
		},
		data() {
			return {
				title: "新建统计表",
				active: 1,
				purchaser: '',
				supplier: '',
				contractTitleCn: '',
				contractTitleEn: '',
				amount: '',
				contractId: '',
				executionStartDate: '',
				executionEndDate: '',
				currency: '',
				usd: '',
				amountPerYear: '',
				contractType: '',
				content: '',
				showPicker: false,
				showPicker2: false,
				showPicker3: false,
				disabledBnt: false,
				partiesList: [],
				releaseLevelList: [],
				proList: [],
				minDate: new Date(1990, 0, 1),
				maxDate: new Date(2060, 10, 1),
				nub: 0,
				rate: '',
				state: '',
				leg: true,
				curreyList: [],
				curreyAllList: [],
				cfileList: [],
				leg: true,
				disabled: true,
				contractName: '',
				ids: '',
				isShowEnglish:true,
				currentDate: new Date(),
				currentDateEnd: new Date()
			};
		},
		mounted() {
			buried("M_result_add_new", "M_add_new_contract_fill");
			let langs = this.getCookie('site_lang')
			if (langs == 'en-US') {
				this.isShowEnglish = false
			}
			if (this.$store.state.exchangeRateList.length !== 0) {
				this.$store.state.exchangeRateList.forEach(item => {
					this.curreyList.push(item.currency)
				})
				this.curreyAllList = this.$store.state.exchangeRateList
			}
			// 成果类型展示
			let type = this.$route.query.type
			this.$store.state.addTypeList.forEach(item => {
				if (item.value == type) {
					this.contractName = item.label
				}
			})
			this.contractType = this.$route.query.type
			this.state = this.$route.query.state
			if (this.state == 'edit')
				this.editContract()
		},
		watch: {
			curreyList2: function(val) {
				if (val.length !== 0) {
					val.forEach(item => {
						this.curreyList.push(item.currency)
					})
					this.curreyAllList = this.$store.state.exchangeRateList
				}
			}
		},
		computed: {
			curreyList2() {
				return this.$store.state.exchangeRateList
			},
		},
		methods: {
			getCookie (cookieName) {
				var strCookie = document.cookie;
				var arrCookie = strCookie.split("; ");
				for (var i = 0; i < arrCookie.length; i++) {
					var arr = arrCookie[i].split("=");
					if (cookieName == arr[0]) {
					  return arr[1];
					}
				}
				return "";
			},
			chooseStarTime(time) {
				this.clearCurrey()
				if (this.executionEndDate == '') {
					this.executionStartDate = this.$moment(time).format("YYYY-MM-DD");
				} else {
					let s = this.monDiff(this.$moment(time).valueOf(), this.$moment(this.executionEndDate).valueOf(), 'day')
					if (s > 0) {
						this.executionStartDate = this.$moment(time).format("YYYY-MM-DD");
					} else {
						Dialog.alert({
							title: this.$t('message.ts'),
							message: this.$t('addMsg.jssjbn'),
						}).then(() => {});
					}
				}
				if (this.executionStartDate !== '' && this.executionEndDate !== '' && this.rate !== '') {
					this.disabled = false
				}
				this.showPicker = false;
			},
			chooseEndTime(time) {
				this.clearCurrey()
				if (this.executionStartDate == '') {
					this.executionEndDate = this.$moment(time).format("YYYY-MM-DD");
				} else {
					let s = this.monDiff(this.$moment(this.executionStartDate).valueOf(), this.$moment(time).valueOf(), 'day')
					if (s > 0) {
						this.executionEndDate = this.$moment(time).format("YYYY-MM-DD");
					} else {
						Dialog.alert({
							title: this.$t('message.ts'),
							message: this.$t('addMsg.jssjbn'),
						}).then(() => {});
					}
				}
				if (this.executionStartDate !== '' && this.executionEndDate !== '' && this.rate !== '') {
					this.disabled = false
				}
				this.showPicker2 = false;
			},
			chooseCurrey(value) {
				this.clearCurrey()
				this.currency = value
				this.$store.state.exchangeRateList.forEach(item => {
					if (item.currency == value)
						this.rate = item.rate
				})
				if (this.executionStartDate !== '' && this.executionEndDate !== '' && this.rate !== '') {
					this.disabled = false
				}
				this.showPicker3 = false;
			},
			amountInput(value) {
					this.usd = ((value * this.rate) / 10000).toFixed(2) * 1;
					if(isNaN(this.usd)){
						this.usd = ''
					}
					if (this.executionStartDate !== '' && this.executionEndDate !== '') {
						let m = this.monDiff(this.$moment(this.executionStartDate).valueOf(), this.$moment(this.executionEndDate).valueOf(),
							'month')	
						if (m > 12) {
							this.amountPerYear = ((this.usd / m) * 12).toFixed(2) * 1;
							if(isNaN(this.amountPerYear)){
								this.amountPerYear = ''
							}
						} else {
							this.amountPerYear = this.usd;
							if(isNaN(this.amountPerYear)){
								this.amountPerYear = ''
							}
						}
					}

			},
			monDiff(startTime, endTime, type) {
				let s = endTime - startTime;
				if (type == 'month') {
					return parseInt(s / 2592000 / 1000);
				} else if (type == 'day') {
					return parseInt(s / 2592000);
				}

			},
			clearCurrey() {
				this.amount = ''
				this.amountPerYear = ''
				this.usd = ''
			},
			addSelect() {
				this.partiesList.push({
					type: '',
					value:'',
					uid:nub++
				});
				if (this.partiesList.length >= 5) {
					this.leg = false
				}
			},
			deletParties(index) {
				this.partiesList.splice(index, 1);
				if (this.partiesList.length < 5) {
					this.leg = true
				}
			},
			async editContract() { //回显信息
				//编辑暂存回显
				const {
					data: res
				} = await this.$axios.get("/api/contract/getContract", {
					id: this.$route.query.id
				})
				if (res.code == 200) {
					// this.$toast('回显成功')
					console.log("回显成功", res.data)
					this.contractType = res.data.contractType
					this.contractName = res.data.contractTypeName
					// 附件回显
					this.cfileList = res.data.ossUrlList

					this.contractTitleCn = res.data.contractTitleCn
					this.contractTitleEn = res.data.contractTitleEn
					this.contractId = res.data.contractId
					this.content = res.data.content
					this.usd = res.data.usd
					this.amount = res.data.amount
					this.amountPerYear = res.data.amountPerYear
					// 时间回显
					this.executionStartDate = res.data.executionStartDate !== 0 ? this.$moment(res.data.executionStartDate).format(
						"YYYY-MM-DD") : ''
					this.executionEndDate = res.data.executionEndDate !== 0 ? this.$moment(res.data.executionEndDate).format(
						"YYYY-MM-DD") : ''
					this.currentDate = new Date(this.executionStartDate)
					this.currentDateEnd = new Date(this.executionEndDate)
					//币种回显
					this.currency = res.data.currencyName
					if (this.curreyAllList.length !== 0) {
						this.curreyAllList.forEach(item => {
							if (item.code == res.data.currency) {
								this.rate = item.rate
							}
						})
					} else {
						console.log('字典币种列表请求失败')
					}
					if (this.executionStartDate !== '' && this.executionEndDate !== ''&&this.executionStartDate !== 0 && this.executionEndDate !== 0 && this.rate !== '') {
						this.disabled = false
					}
					//供应商采购商回显
					this.client = JSON.parse(res.data.client);
					this.purchaser = this.client[0].value;
					this.supplier = this.client[1].value;
					if (this.client.length !== 0) {
						this.client.shift();
						this.client.shift();
					}
					this.partiesList = this.client;
					if (this.partiesList.length >= 5) {
						this.leg = false
					}
				} else {
					this.$toast('回显失败')
				}
			},
			beforSubmit() {
				// 获取附件
				let ossUrlLists = []
				if (this.$refs.uploadFile.fileList.length !== 0) {
					ossUrlLists = this.$refs.uploadFile.fileList
				}
				// 供应商
				this.proList = [];
				let str1 = ''
				let str2 = ''
				if (this.$refs.select !== undefined) {
					this.$refs.select.forEach(item => {
						this.proList.push(item.obj);
						if (item.obj.type == '1') {
							str1 += item.obj.value;
						} else if (item.obj.type == '2') {
							str2 += item.obj.value;
						}
					});
				}
				this.proList.unshift({
					type: '2',
					value: this.supplier
				});
				this.proList.unshift({
					type: '1',
					value: this.purchaser
				});
				let client = JSON.stringify(this.proList);
				// 币种
				let currencyCode = ''
				if (this.curreyAllList.length !== 0) {
					this.curreyAllList.forEach(item => {
						if (item.currency == this.currency) {
							currencyCode = item.code
						}
					})
				}


				let obj = {
					amount: Number(this.amount),
					usd: Number(this.usd),
					amountPerYear: Number(this.amountPerYear),
					currency: currencyCode,
					content: this.content,
					contractId: this.contractId,
					executionStartDate: this.$moment(this.executionStartDate).valueOf(),
					executionEndDate: this.$moment(this.executionEndDate).valueOf(),
					contractTitleCn: this.contractTitleCn,
					contractTitleEn: this.contractTitleEn,
					ossUrlList: ossUrlLists,
					client: client,
					purchaser: this.purchaser + str1,
					supplier: this.supplier + str2,
					contractType: this.contractType
				}
				delete obj.createTime;
				delete obj.modifiedTime;
				delete obj.submitTime;
				delete obj.approvalTime;
				delete obj.approvalStatus
				return obj
			},
			beforBnt() { //上一步
				if (this.$route.query.id && this.$route.query.id !== '') {
					this.$router.push('/addPage')
				} else {
					Dialog.confirm({
						title: this.$t('message.ts'),
						message: this.$t('lackMsg.wbcsfbc'),
					}).then(() => {
						this.save()
					}).catch(() => {
						this.$router.push('/addPage')
					});
				}

			},
			onSubmit(value) { //下一步
				// let params = this.beforSubmit()
				// if (this.$route.query.id) {
				// 	params.id = this.$route.query.id
				// }
				// this.$router.push({
				// 	path: '/contractThirdly',
				// 	query: params
				// })
				this.save('next')
			},
			async save(isAlert) {
				this.disabledBnt = true
				let params = this.beforSubmit()
				this.state = this.$route.query.state

				if (this.state == 'edit') { // 编辑下的暂存
					params.id = this.$route.query.id || "";
					const {
						data: res
					} = await this.$axios.post("/api/contract/updateContract", params)
					if (res.code == 200) {
						this.disabledBnt = false
						if(isAlert == 'next'){
							this.$router.push({
								path: '/contractThirdly',
								query: params
							})
						}else{
							this.$toast(this.$t('message.zccg'))
						}
					} else {
						this.disabledBnt = false
						this.$toast(this.$t('message.zcsb'))
					}
				} else { //新建下的暂存
					const {
						data: res
					} = await this.$axios.post("/api/contract/contractDraft", params)
					// console.log(res)
					if (res.code == 200) {
						this.disabledBnt = false
						if(isAlert == 'next'){
							params.id = res.data
							this.$router.push({
								path: '/contractThirdly',
								query: params
							})
						}else{
							this.$toast(this.$t('message.zccg'))
							this.$router.push({
								path: '/contractSecond',
								query: {
									state: 'edit',
									id: res.data
								}
							})
						}
					} else {
						this.$toast(this.$t('message.zcsb'))
					}
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.step-box {
		padding: 15px;
	}
	.out {
		/*width: 96%;*/
		/*background-color: #FFFFFF;*/
		margin: 15px;
		border-radius: 8px;
	}

	.box {
		width: 100%;
		background-color: #ffffff;
		margin: 12px auto;
		border-radius: 8px;
	}

	.inner {
		width: 100%;
	}

	.contrantType {
		/*padding: 15px 0 3px 10px;*/
		/*color: #646566;*/
		height: 44px;
		line-height: 44px;
		font-weight: 600;
		border-bottom: 1px solid #e6e9ee;
		margin-bottom: 26px;
		padding-left: 10px;
	}

	.textrea {
		border: 1px solid #e6e9ee;
		margin: 0 auto;
		border-radius: 2px;
	}
	.none-border::after{
		border: 0 solid #FFFFFF !important;
	}
	.out-textrea {
		width: 100%;
		text-align: center;

		::v-deep .textrea {
			width: 95%;
		}

		::v-deep .van-field__error-message {
			text-align: left !important;
		}
	}

	.c-title {
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 550;
		color: rgba(33, 33, 33, 1);
		padding: 12px 0px 0 10px;
	}

	.add-title {
		width: 95%;
		border-bottom: 1px solid #e6e9ee;
		color: #212121;
		font-size: 14px;
		padding: 14px 0;
		margin: 6px auto;
		font-weight: 550;
	}

	.addBnt {
		background-color: #fe8c01;
		margin: 10px 0 10px 10px;
		border-radius: 4px;
		font-size: 13px;
		color: #ffffff;
		padding: 4px 8px;
	}

	.add-title p {
		border-left: 3px solid #ffbc3a;
		padding-left: 5px;
	}

	.save {
		background: linear-gradient(90deg,
			rgba(254, 207, 71, 1) 0%,
			rgba(255, 188, 57, 1) 100%) !important;
		border-radius: 24px !important;
		border: none !important;
		font-size: 16px !important;
	}

	.mybnt {
		background: rgba(255, 255, 255, 1);
		border-radius: 22px;
		border: 1px solid rgba(204, 207, 212, 1);
		color: rgba(102, 102, 102, 1);
		font-size: 17px;
		width: 49%;
	}
</style>
